package com.cheers.service.impl;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.util.StringUtils;

import com.cheers.common.Constants;
import com.cheers.dao.UserDao;
import com.cheers.model.Promoter;
import com.cheers.model.User;
import com.cheers.service.UserService;
import com.cheers.util.MD5Util;

public class UserServiceImpl extends AbstractServiceImpl implements UserService {

	@Resource
	private UserDao userDao;
	
	@Override
	public String mod(String userId, String password, String address,
			String mobile) throws Exception {
		//获取用户信息
		User user = userDao.get(User.class, userId);
		if (user == null) {
			return Constants.USER_CODE;
		}
		
		//修改用户信息
		if (!StringUtils.isEmpty(password)) {
			user.setPassword(MD5Util.getMD5(password));
		}
		user.setAddress(address);
		user.setMobile(mobile);
		userDao.save(user);
		return Constants.OK;
	}
	
	@Override
	public String login(String username, String password) throws Exception {
		//密码加密
		String md5 = MD5Util.getMD5(password);
		
		//获取用户
		User user = userDao.getUserByUsernamePassword(username, md5);
		if (user != null) {
			return user.getId();
		}
		return null;
	}
	
	@Override
	public boolean exist(String username) throws Exception {
		return userDao.hasUserByUsername(username);
	}
	
	@Override
	public String apply(String userId, String realname, String address,
			String mobile, String qq, String job) throws Exception {
		User user = userDao.get(User.class, userId);
		if (user == null) {
			return Constants.USER_CODE;
		}
		
		Promoter promoter = new Promoter();
		promoter.setUserId(userId);
		promoter.setRealname(realname);
		promoter.setAddress(address);
		promoter.setMobile(mobile);
		promoter.setQq(qq);
		promoter.setJob(job);
		promoter.setStatus(0);
		promoter.setCtime(new Date());
		userDao.save(promoter);
		return promoter.getId();
	}

	@Override
	public String register(String username, String password, String email) throws Exception {
		User user = new User();
		user.setUsername(username);
		user.setPassword(MD5Util.getMD5(password));
		user.setEmail(email);
		user.setCtime(new Date());
		userDao.save(user);
		return user.getId();
	}
}
